package com.p2l.letterblocks;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Paint.Align;

public class Button extends Sprite {
	private Bitmap[] bitmap;
	private GamePersistor persistor;
	private Paint p;
	private Rect bounds;
	
	private String text;
	
	private boolean enabled;
	private boolean round;
	
	public Button(GamePersistor persistor, float x, float y, float height, float width, boolean round, String text, Bitmap[] bitmap) {
		super(x, y, height, width, null);
		this.persistor = persistor;
		this.bitmap = bitmap;
		this.round = round;
		this.text = text;
		this.enabled = false;
		
		bounds = new Rect();
		
		p = new Paint();
		p.setTextSize(persistor.getResources().getDimension(R.dimen.button_ingame));
		p.setTextAlign(Align.CENTER);
	}

	public boolean isEnabled() {
		return enabled;
	}

	public void setEnabled(boolean enabled) {
		this.enabled = enabled;
	}

	@Override
	public void onDraw(Canvas c, int delta, float x) {
		Rect r = new Rect((int)getX(), (int)getY(), (int)(getX() + getWidth()), (int)(getY() + getHeight()));
		float n = 0f;
		if (persistor.hand == 1 && persistor.getModel().getBear().getLastKnownDirection().getX() < 0)
			n += persistor.getModel().getBear().getWidth();
		else if (persistor.hand == 0 && persistor.getModel().getBear().getLastKnownDirection().getX() > 0)
			n -= persistor.getModel().getBear().getWidth();
		
		if (x > (GamePersistor.SCREEN_WIDTH * 0.775f) + n && persistor.hand == 1 || x < (GamePersistor.SCREEN_WIDTH * 0.225) + n && persistor.hand == 0)
			c.drawBitmap(bitmap[1], null, r, getPaint());
		else
			c.drawBitmap(bitmap[0], null, r, getPaint());
		
		if (!text.equals("")) {
			p.getTextBounds(text, 0, text.length(), bounds);
		    int newY = (int)((getHeight() + bounds.height()) / 2); 
			int newX = (int)(getX() - x + (getWidth() / 2));
			
			c.drawText(text, newX, getY() + newY, p);
		}
	}
	
	public boolean isPressed(float x, float y) {
		if (round) {
			double a = Math.pow((getX() + (getWidth() / 2)) - x, 2);
			double b = Math.pow((getY() + (getWidth() / 2)) - y, 2);
			double c = Math.sqrt(a + b);
			
			if (c < getWidth() / 2)
				return true;
			else
				return false;
		} else {
			if (getX() <= x && getX() + getWidth() >= x && getY() <= y && getY() + getHeight() >= y)
				return true;
			else
				return false;
		}
	}
}